package com.android.rapidcash.activitys

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import android.webkit.*
import com.afollestad.materialdialogs.utils.MDUtil.isLandscape
import com.android.lib.base.baseclass.BaseVMActivity
import com.android.rapidcash.viewmodel.MainViewModel
import com.blankj.utilcode.util.ToastUtils
import com.rapidcash.abanca.santander.vivus.revolut.waylet.libertex.icmarkets.caixabank.R
import com.rapidcash.abanca.santander.vivus.revolut.waylet.libertex.icmarkets.caixabank.databinding.ActivityWebBinding
import java.util.*


class WebActivity : BaseVMActivity<MainViewModel, ActivityWebBinding>() {

    private val mUrl by lazy {
        intent.getStringExtra("url")!!
    }
    private val mTitle by lazy {
        intent.getStringExtra("title")!!
    }

    private var mTimer: Timer? = null


    private val timeout = 5000L;//超时时间;//计时器

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.topBar.mTvTitle.text = mTitle
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun initData() {

        val settings: WebSettings = mBinding.webView.settings

        settings.domStorageEnabled = true;//是否支持 Local Storage
        settings.javaScriptEnabled = true;//支持JavaScript
        settings.useWideViewPort = true;//使WebView具有普通的视口(例如普通的桌面浏览器)
        settings.loadWithOverviewMode = true;//加载完全缩小的WebView
        settings.setSupportZoom(true);// 设置可以支持缩放
        settings.builtInZoomControls = true;// 设置启用缩放功能
        settings.displayZoomControls = true;//显示缩放控制按钮
        settings.javaScriptCanOpenWindowsAutomatically = true;
        //开启支持多窗口
        settings.setSupportMultipleWindows(true);

        mBinding.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(mUrl);
                return false
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {

                val task = object : TimerTask() {
                    override fun run() {
                        /* * 超时后,首先判断页面加载是否小于100,就执行超时后的动作 */
                        if (mBinding.webView.progress < 100) {
                            mTimer?.cancel()
                            mTimer?.purge()
                            ToastUtils.showShort(getString(R.string.timeout))
                        }
                    }
                }
                mTimer = Timer()
                mTimer?.schedule(task, timeout, 1L)

            }

            override fun onPageFinished(view: WebView?, url: String?) {
                mTimer?.cancel()
                mTimer?.purge()

            }
        }

        mBinding.webView.loadUrl("https://www.baidu.com")
    }

    override fun onDestroy() {
        super.onDestroy()
        mTimer?.cancel()
        mTimer?.purge()
        mTimer = null
    }

}